//
//  AppMemCache.m
//  helper
//
//  Created by huangyi on 12-11-21.
//  Copyright (c) 2012年 huangyi. All rights reserved.
//

#import "KVDBObj.h"
#import "NSString+utils.h"
#import "NSString+path.h"

@interface KVDBObj ()

@property(nonatomic,strong)NSString *file;
@property(nonatomic,strong)NSMutableDictionary *store;

@end

@implementation KVDBObj

-(void)dealloc{
    [self save];
}
-(KVDBObj*)init{
    return [self initKVDB:nil];
}
+(KVDBObj*)shared{
    static KVDBObj *singleton=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *filename=@"app.bin".docPath;
        singleton=[[KVDBObj alloc] initKVDB:filename];
    });
    return singleton;
}
-(id)initKVDB:(NSString*)filename{
    self=[super init];
    if (self) {
        self.file=filename;
        [self reload];
    }
    return self;
}
-(NSString*)absolutePath{
    return self.file;
}

-(id)key:(NSString*)key{
    id value=nil;
    if (key) {
        value=[self.store valueForKey:key];
    }
    return value;
}
-(BOOL)key:(NSString*)key value:(id)value{
    if (key) {
        if (value) {
            [self.store setValue:value forKey:key];
        }else{
            [self.store removeObjectForKey:key];
        }
        return YES;
    }else{
        return NO;
    }
}

-(BOOL)save{
    if (self.file) {
        NSString *tmp=(uniqueID()).tempPath;
        if ([NSKeyedArchiver archiveRootObject:self.store toFile:tmp]) {
            if (self.file.isFile) {
                [self.file removeFile];
            }
            return [tmp moveTo:self.file];
        }else{
            NSLog(@"AppKVDB: save failed inside NSKeyedArchiver");
            return NO;
        }
    }else{
        NSLog(@"AppKVDB: file not set");
        return NO;
    }
}
-(BOOL)clear{
    [self.store removeAllObjects];
    if (self.file) {
        [self save];
    }
    return YES;
}

-(void)reload{
    self.store=[NSMutableDictionary dictionary];
    if (self.file) {
        if (self.file.isFile) {
            self.store=[NSKeyedUnarchiver unarchiveObjectWithFile:self.file];
        }else{
            [self save];
        }
    }
}

@end
